package Sever端;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketSever extends Thread {
    private static final Object R = new Object();
    private static boolean isRun = false;
    private static boolean isExif = true;

    public void Wake() {
        isRun = true;
        System.out.println("开启服务端");
        synchronized (R) {
            R.notify();
        }
    }

    public void Interrupt() {
        isRun = false;
        System.out.println("服务器中断！");
    }

    public void Stop() {
        isRun = false;
        isExif = false;
    }

    public void run() {
        try {
            // 创建服务端socket
            ServerSocket serverSocket = new ServerSocket(9999);
            // 创建客户端socket
            Socket socket;
            InetAddress addr = InetAddress.getLocalHost();
            System.out.println("Local HostAddress: " + addr.getHostAddress());
            //循环监听等待客户端的连接
            synchronized (R) {
                while (isExif) {//是否存在
                    if (isRun) {//是否运行
                        System.out.println("开始等待");
                        socket = serverSocket.accept();
                        new ServerThread(socket).start();
                        // 监听客户端
                    } else {
                        sleep(100);
                        R.wait();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
